package com.qujia.station.service.impl;
import java.math.BigDecimal;
import java.time.LocalDateTime;

import java.sql.Timestamp;
import java.util.*;

import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.enums.ErrorCode;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.LocalDateTimeUtil;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.station.controller.CouponActivityController;
import com.qujia.station.domain.*;
import com.qujia.station.mapper.AppUserSuperMapper;
import com.qujia.station.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author qujia
 * @date 2021-11-30
 */
@Service
public class AppUserSuperServiceImpl implements IAppUserSuperService
{
    @Autowired
    private AppUserSuperMapper appUserSuperMapper;

    @Autowired
    private IAppUserInfoService appUserInfoService;

    @Autowired
    private IAppUserSuperDetailService appUserSuperDetailService;

    @Autowired
    private CouponActivityController couponActivityController;
    @Autowired
    private ISuperPayOrderService superPayOrderService;
    @Autowired
    private IStationService stationService;

    /**
     * 查询【请填写功能名称】
     * 
     * @param superId 【请填写功能名称】ID
     * @return 【请填写功能名称】
     */
    @Override
    public AppUserSuper selectAppUserSuperById(Long superId)
    {
        return appUserSuperMapper.selectAppUserSuperById(superId);
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param appUserSuper 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<AppUserSuper> selectAppUserSuperList(AppUserSuper appUserSuper)
    {
        return appUserSuperMapper.selectAppUserSuperList(appUserSuper);
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param appUserSuper 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertAppUserSuper(AppUserSuper appUserSuper)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();
        appUserSuper.setEnable(1);
        appUserSuper.setEnterpriseId(user.getEnterpriseId());
        return appUserSuperMapper.insertAppUserSuper(appUserSuper);
    }

    @Override
    public String insertAppUserSuperPhone(AppUserSuper appUserSuper) {

        if (appUserSuper.getEnterpriseId()==null) {
            throw new CustomException(ErrorCode.ENTERPRISE_NOT_FOUND);
        }
        String[] phons=appUserSuper.getPhone().split("\n");
        StringBuilder builder=new StringBuilder();
        SysAppUserInfo query = new SysAppUserInfo();
        query.setStationId(appUserSuper.getEnterpriseId());
        AppUserSuper appUserSuper1 =  appUserSuperMapper.selectAppUserSuperById(appUserSuper.getSuperId());
        String couponIssueIds =   appUserSuper1.getCouponIssueIds();
        List<String> couponIds = Collections.emptyList();
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(couponIssueIds)) {
            String[] split = couponIssueIds.split(",");
            couponIds = Arrays.asList(split);
        }
        appUserSuper1.getEnterpriseId();

        Station station = new Station();
        station.setEnterpriseId(appUserSuper1.getEnterpriseId());
        station.setDeleteStatus("0");
        List<Station> stations = stationService.selectStationList(station);
        Integer stationId = null;
        if (!stations.isEmpty()) {
            stationId = Math.toIntExact(stations.get(0).getStationId());
        }

        for (String item:phons ) {
            //SysAppUserInfo info=appUserInfoService.selectAppUserInfoByPhone(appUserSuper.getPhone());
            query.setMobilePhone(item);
            try {
                couponActivityController.drawCouponsSuper(couponIds,item,appUserSuper1.getEnterpriseId());
            } catch (Exception e) {
                // 在这里处理异常，可以打印错误信息或执行其他操作
                System.out.println(e);
            }
            SysAppUserInfo info = appUserInfoService.getOne(query);
            if(info ==null || StringUtils.isEmpty(info.getUserId().toString())){
                builder.append("暂无").append(item).append("手机号会员\n");
                continue;
            }
            //判断如果之前是超级会员，endDate在之前的基础上增加
            AppUserSuperDetail superDetail = new AppUserSuperDetail();
            superDetail.setEnterpriseId(appUserSuper.getEnterpriseId());
            superDetail.setUserId(Long.valueOf(info.getUserId().toString()));
            List<AppUserSuperDetail> appUserSuperDetails = appUserSuperDetailService.selectAppUserSuperDetailList(superDetail);
//            AppUserSuperDetail appUserSuperDetail = appUserSuperDetailService.selectAppUserSuperDetailById(Long.valueOf(info.getUserId().toString()));
            AppUserSuperDetail appUserSuperDetail = null;
            if(appUserSuperDetails != null && appUserSuperDetails.size()>0){
                appUserSuperDetail = appUserSuperDetails.get(0);
            }
            Date superStartDate = null;
            if(appUserSuperDetail != null){
                Date endDate = appUserSuperDetail.getEndDate();
                appUserSuperDetail.setOpeningMode(0);
                appUserSuperDetail.setEnable(0);
                if(endDate.before(new Date())){
                    //已经过期
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(new Date());
                    cal.add(Calendar.DATE,  appUserSuper1.getCycle().intValue());
                    appUserSuperDetail.setEndDate(cal.getTime());
                    appUserSuperDetail.setSuperId(appUserSuper1.getSuperId());
                    appUserSuperDetailService.updateAppUserSuperDetail(appUserSuperDetail);
                }else{
                    superStartDate = endDate;
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(endDate);
                    cal.add(Calendar.DATE,  appUserSuper1.getCycle().intValue());
                    appUserSuperDetail.setEndDate(cal.getTime());
                    appUserSuperDetail.setSuperId(appUserSuper1.getSuperId());
                    appUserSuperDetailService.updateAppUserSuperDetail(appUserSuperDetail);
                }
            }else{
                AppUserSuperDetail detail=new AppUserSuperDetail();
                detail.setBeginDate(new Timestamp(System.currentTimeMillis()));
                Date date = new Date();
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);
                cal.add(Calendar.DATE,  appUserSuper1.getCycle().intValue());
                detail.setEndDate(cal.getTime());
                detail.setUserId(Long.valueOf(info.getUserId().toString()));
                detail.setSuperId(appUserSuper1.getSuperId());
                detail.setCreatby(info.getName());
                detail.setEnable(0);
                detail.setOpeningMode(0);
                detail.setEnterpriseId(appUserSuper1.getEnterpriseId());
                appUserSuperDetailService.insertAppUserSuperDetail(detail);
            }
            LocalDateTime now = superStartDate == null ? LocalDateTime.now() : LocalDateTimeUtil.parseLdt(superStartDate);
            SuperPayOrder superPayOrder = new SuperPayOrder();
            superPayOrder.setSuperOrderNo(StringUtils.generateOrdNo());
            superPayOrder.setAppUserId(Math.toIntExact(info.getUserId()));
            superPayOrder.setAppUserName(info.getBlogNickName());
            superPayOrder.setSuperId(Math.toIntExact(appUserSuper1.getSuperId()));
            superPayOrder.setSuperName(appUserSuper1.getSuperName());
            superPayOrder.setPayType("imp");
            superPayOrder.setAmt(BigDecimal.ZERO);
            superPayOrder.setCreateTime(now);
            superPayOrder.setStatus("2");
            superPayOrder.setMobilePhone(info.getMobilePhone());
            superPayOrder.setStationId(stationId);
            superPayOrder.setEnterpriseId(Math.toIntExact(info.getStationId()));
            superPayOrder.setCycle(appUserSuper1.getCycle());
            superPayOrder.setSuperStartTime(now);
            superPayOrder.setSuperEndTime(now.plusDays(appUserSuper1.getCycle()));
            superPayOrderService.save(superPayOrder);
        }
        return builder.toString();
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param appUserSuper 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateAppUserSuper(AppUserSuper appUserSuper)
    {
        return appUserSuperMapper.updateAppUserSuper(appUserSuper);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param superIds 需要删除的【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteAppUserSuperByIds(Long[] superIds)
    {
        return appUserSuperMapper.deleteAppUserSuperByIds(superIds);
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param superId 【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteAppUserSuperById(Long superId)
    {
        return appUserSuperMapper.deleteAppUserSuperById(superId);
    }
}
